#include "thread_pool.h"
#include "mysql/mysql.h"
#include "user.h"

extern ListNode * userList;
extern char server_wd[1024];

void back_pre_wd(char * str){
    int len = strlen(str);
    while(1){
        if(str[len-1]!='/'){
            len--;
        }else{
            str[len-1] = '\0';
            break;
        }
    }
}

/*
   Eddie made cdCommand
   */
//*
void cdCommand(task_t * task)
{
    //通过peerfd遍历所有已连接用户链表，修改pwd,pre_wd
    ListNode * p = userList;
    while(p){
        if(p->val->peerfd != task->peerfd || p->val->login_status == LOGIN_OUT){
            p = p->next;
        }else{
            //先获取将要改变的工作路径
            user_info *user = p->val;
            //如果path是.. 先判断当前路径是否为serve端所在的目录
            if(!strcmp(task->data,"..")){
                if(!strcmp(user->pwd,server_wd)){
                    //如果是当前目录，就显示cd失败
                }else{
                    //退回父目录
                    //pre变为cur
                    strcpy(user->pre_wd , user->pwd);           
                    //cur通过查表找到其parent的pwd替换,分离pwd
                    back_pre_wd(user->pwd);
                }
            }else if(!strcmp(task->data,".")){
                strcpy(user->pre_wd,user->pwd);
            }else if(!strcmp(task->data,"-")){
                //退回上一次操作的目录
                //交换pre和cur
                char temp[1024] = {0};
                strcpy(temp,user->pwd);
                strcpy(user->pwd,user->pre_wd);
                strcpy(user->pre_wd,temp);
            }else if(!strcmp(task->data,"~")){
                strcpy(user->pre_wd,user->pwd);
                strcpy(user->pwd,server_wd);
            }else{
                //TODO:通过filename查询新的工作目录是否存在
                int ret = select_file_cd(user,task->data);
                if(ret){
                    char path[1024] = {0};
                    snprintf(path,sizeof(path),"%s/%s",user->pwd,task->data);
                    //更新当前目录和之前的目录
                    strcpy(user->pre_wd,user->pwd);
                    strcpy(user->pwd,path);
                }
            }
        }
        break;
    }
}

